﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.templates;

namespace l1cs.server.model
{
    public class L1ShopBuyOrder
    {
        private L1ShopItem _item;
        private int _count;

        public L1ShopBuyOrder( L1ShopItem item, int count )
        {
            _item = item;
            _count = count;
        }

        public L1ShopItem getItem()
        {
            return _item;
        }

        public int getCount()
        {
            return _count;
        }
    }

    public class L1ShopBuyOrderList
    {
        private static Logger _log = Logger.getLogger( typeof( L1ShopBuyOrder ).FullName );

        private L1Shop _shop;
        private List<L1ShopBuyOrder> _list = new List<L1ShopBuyOrder>();
        private L1TaxCalculator _taxCalc;

        private int _totalWeight = 0;
        private int _totalPrice = 0;
        private int _totalPriceTaxIncluded = 0;

        public L1ShopBuyOrderList( L1Shop shop )
        {
            _shop = shop;
            _taxCalc = new L1TaxCalculator( shop.getNpcId() );
        }

        public void add( int orderNumber, int count )
        {
            if ( _shop.getSellingItems().Count < orderNumber )
            {
                return;
            }
            L1ShopItem shopItem = _shop.getSellingItems()[orderNumber];

            int price = (int)( shopItem.getPrice() * Config.RATE_SHOP_SELLING_PRICE );
            // オーバーフローチェック
            for ( int j = 0; j < count; j++ )
            {
                if ( price * j < 0 )
                {
                    return;
                }
            }
            if ( _totalPrice < 0 )
            {
                return;
            }
            _totalPrice += price * count;
            _totalPriceTaxIncluded += _taxCalc.layTax( price ) * count;
            _totalWeight += shopItem.getItem().getWeight() * count
                    * shopItem.getPackCount();

            if ( shopItem.getItem().isStackable() )
            {
                _list.Add( new L1ShopBuyOrder( shopItem, count
                        * shopItem.getPackCount() ) );
                return;
            }

            for ( int i = 0; i < ( count * shopItem.getPackCount() ); i++ )
            {
                _list.Add( new L1ShopBuyOrder( shopItem, 1 ) );
            }
        }

        public List<L1ShopBuyOrder> getList()
        {
            return _list;
        }

        public int getTotalWeight()
        {
            return _totalWeight;
        }

        public int getTotalPrice()
        {
            return _totalPrice;
        }

        public int getTotalPriceTaxIncluded()
        {
            return _totalPriceTaxIncluded;
        }

        public L1TaxCalculator getTaxCalculator()
        {
            return _taxCalc;
        }
    }
}
